package com.anxin.controller;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.anxin.common.utils.ImgUtils;
import com.anxin.common.utils.JsonResult;
import com.anxin.service.IImgCaptchaRemoteService;

@Controller
@RequestMapping("common")
public class CommonController  {

	private static final Logger logger = LoggerFactory.getLogger(CommonController.class);

	/**
	 * 图片验证码个数
	 */
	private static final int CODE_NUM = 4;

	@Autowired
	private IImgCaptchaRemoteService imgCaptchaRemoteService;

	/**
	 * 生成图片验证码
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws BaseException
	 */
	@ResponseBody
	@RequestMapping(value = "imgCode", method = RequestMethod.GET)
	public void imgCode(HttpServletRequest request, HttpServletResponse response, @RequestParam("token") String token) {

		// 设置响应的类型格式为图片格式
		response.setContentType("image/jpeg");
		// 禁止图像缓存。
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);

		// 去掉 I和1 0和O
		byte[] bytes = null;
		OutputStream out = null;
		try {

			String code = imgCaptchaRemoteService.genCaptcha(token, CODE_NUM, 0);
			bytes = ImgUtils.generateCaptchaImage(code);

			out = response.getOutputStream();
			out.write(bytes);
			out.flush();
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {

			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					logger.error("OutputStream close is error,{}", e);
				}
			}
		}
	}
	
}
